<!DOCTYPE html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>
// This test aims to ensure that OffscreenCanvas.commit() does not
// crash for a placeholder canvas under frameless document.
// Since the document is invisible, the resultant image should be
// not visible too. But users must be able to draw to the OffscreenCanvas
// and do canvas-operations on the frameless placeholder canvas.
function createFramelessCanvas() {
  var framelessDoc = document.implementation.createHTMLDocument("frameless");
  var canvas = framelessDoc.createElement("canvas");
  canvas.width = 50;
  canvas.height = 50;
  return canvas;
}

function transferControlAndCommit(canvas) {
  var offscreenCanvas = canvas.transferControlToOffscreen();
  var ctx = offscreenCanvas.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(0, 0, 50, 50);
  return offscreenCanvas;
}

// See crbug.com/1254125
test(function() {
  var canvas = createFramelessCanvas();
  canvas.transferControlToOffscreen();
  assert_throws_dom("InvalidStateError", function() {canvas.transferControlToOffscreen()});
}, "Verify that transferring a frameless canvas twice throws an error and does not cause a crash");

test(function() {
  var offscreenCanvas = transferControlAndCommit(createFramelessCanvas());
  var ctx = offscreenCanvas.getContext("2d");
  var pixels =  ctx.getImageData(0, 0, 1, 1).data;
  assert_array_equals(pixels, [0, 0, 255, 255]);
}, "Verify that the getImageData() works on the OffscreenCanvas context of a frameless canvas");

async_test(function(t) {
  var canvas = createFramelessCanvas();
  var offscreenCanvas = transferControlAndCommit(canvas);

  var c = document.createElement("canvas");
  c.width = 50;
  c.height = 50;
  var ctx2 = c.getContext("2d");
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      ctx2.drawImage(canvas, 0, 0);
      var pixels = ctx2.getImageData(0, 0, 1, 1).data;
      t.step(() => {
        assert_array_equals(pixels, [0, 0, 255, 255]);
      });
      t.done();
    }, 0);
  });
}, "Verify that the placeholder canvas can be used as an image source");
</script>
